'use client';

import { NextIntlClientProvider } from 'next-intl';
import { createContext, useContext, useState, ReactNode } from 'react';

// 导入翻译文件
import zhMessages from '@/messages/zh.json';
import enMessages from '@/messages/en.json';

// 定义支持的语言类型
type Locale = 'zh' | 'en';

// 语言映射
const messages: Record<Locale, any> = {
  zh: zhMessages,
  en: enMessages,
};

// 创建语言切换的 Context
interface LocaleContextType {
  locale: Locale;
  setLocale: (locale: Locale) => void;
}

const LocaleContext = createContext<LocaleContextType | undefined>(undefined);

// 自定义 Hook：用于在组件中切换语言
export function useLocale() {
  const context = useContext(LocaleContext);
  if (!context) {
    throw new Error('useLocale must be used within IntlProvider');
  }
  return context;
}

interface IntlProviderProps {
  children: ReactNode;
}

export function IntlProvider({ children }: IntlProviderProps) {
  // 默认语言为中文
  const [locale, setLocale] = useState<Locale>('zh');

  return (
    <LocaleContext.Provider value={{ locale, setLocale }}>
      <NextIntlClientProvider
        locale={locale}
        messages={messages[locale]}
        timeZone="Asia/Shanghai"
      >
        {children}
      </NextIntlClientProvider>
    </LocaleContext.Provider>
  );
}
